//
//  SheetDetailController.swift
//  歌单详情
//
//  Created by smile on 2019/6/13.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//导入发布订阅框架
import SwiftEventBus

//导入日志框架
import CocoaLumberjack

class SheetDetailController: BaseMusicPlayerController {
    
    /// 背景容器的高度约束
    @IBOutlet weak var backgroundContainerHeight: NSLayoutConstraint!
    
    /// 背景
    @IBOutlet weak var ivBackground: UIImageView!
    
    /// 列表控件
    @IBOutlet weak var tableView: UITableView!
    
    /// 歌单Id
    var id:String!
    
    /// 歌单
    var data:Sheet!
    
    /// 列表数据
    var dataArray:[Song] = []
    
    /// 头部
    var header:SheetDetailHeaderView!
    
    override func initViews() {
        super.initViews()
        
        setTitle("歌单")
        
        //设置数据源和代理
        //这里使用的代码设置
        //在发现页面使用的是可视化
        //两者功能上没什么区别
        //大家可以看情况选择
        tableView.dataSource=self
        tableView.delegate=self
        
        //注册Header
        tableView.register(UINib(nibName: SheetDetailHeaderView.NAME, bundle: nil), forHeaderFooterViewReuseIdentifier: SheetDetailHeaderView.NAME)
        
        //注册Cell
        tableView.register(UINib(nibName: SongListCell.NAME, bundle: nil), forCellReuseIdentifier: SongListCell.NAME)
        
        //添加右侧按钮
        //分享
        let shareBarItem = UIBarButtonItem(image: UIImage(named: "Share"), style: .plain, target: self, action: #selector(onShareClick(sender:)))
        
        //更多
        let moreBarItem = UIBarButtonItem(image: UIImage(named: "MoreWhite"), style: .plain, target: self, action: #selector(onMoreClick(sender:)))
        
        //将button添加到导航栏右侧
        //从右到左
        navigationItem.rightBarButtonItems = [createPlayingBar(),moreBarItem,shareBarItem]
    }
    
    /// 返回播放状态图片前缀
    ///
    /// - Returns: <#return value description#>
    override func getPlayingBarImagePrefix() -> String {
        return "TatbarPlayingWhite"
    }
    
    /// 分享按钮点击了
    ///
    /// - Parameter sender: <#sender description#>
    @objc func onShareClick(sender:UIButton) {
        print("SheetDetailController onShareClick")
    }
    
    /// 更多按钮点击了
    ///
    /// - Parameter sender: <#sender description#>
    @objc func onMoreClick(sender:UIButton) {
        print("SheetDetailController onMoreClick")
    }
    
    override func initDatas() {
        super.initDatas()
        //获取数据
        Api.shared.sheetDetail(id: id).subscribeOnSuccess { data in
            if let data = data?.data {
                self.showData(data)
            }
        }.disposed(by: disposeBag)
    }
    
    /// 显示数据
    ///
    /// - Parameter data: <#data description#>
    func showData(_ data:Sheet) {
        self.data=data
        
        //显示背景
        ImageUtil.show(ivBackground, data.banner)
        
        //显示头部数据
        header.bindData(data)
        
        if let songs = data.songs {
            //添加歌曲数据
//            for i in 1...100 {
                dataArray = dataArray+songs
//            }
            
            //重新加载数据
            tableView.reloadData()
        }
    }
    
    /// 处理收藏和取消收藏逻辑
    func processCollectionClick() {
        if data.isCollection() {
            //已经收藏了
            
            //取消收藏
            Api.shared.deleteCollect(data.id).subscribeOnSuccess { data in
                //取消收藏成功
                self.data.collection_id = nil
                
                //收藏数-1
                self.data.collections_count -= 1
                
                //刷新收藏状态
                self.header.showCollectionStatus()
                
                //发布通知
                SwiftEventBus.post(ON_SHEET_CHANGED)
            }.disposed(by: disposeBag)
        } else {
            //没有收藏
            
            //收藏
            Api.shared.collect(data.id).subscribeOnSuccess { (data) in
                //收藏成功
                
                //收藏状态变更后
                //可以重新点击歌单详情界面
                //获取收藏状态
                //但对于收藏来说
                //收藏数可能没那么重要
                //所以不用及时刷新
                
                self.data.collection_id = 1
                
                //收藏数量+1
                self.data.collections_count += 1
                
                //刷新收藏状态
                self.header.showCollectionStatus()
                
                //发布通知
                SwiftEventBus.post(ON_SHEET_CHANGED)
            }.disposed(by: disposeBag)
        }
    }
    
    /// 选中当前播放的音乐
    func scrollPosition() {
        //判断当前歌单是否有音乐
        if dataArray.count > 0 {
            //判断是否有播放音乐
            if let data = playListManager.data {
                //有播放的音乐
                
                var index = -1
                
                //遍历当前歌单所有音乐
                //找到正在播放的音乐
                for e in dataArray.enumerated() {
                    if e.element.id == data.id {
                        index = e.offset
                        break
                    }
                }
                
                if index != -1 {
                    //创建一个indexPath
                    let indexPath = IndexPath(item: index, section: 0)
                    
                    //选中这一行
                    tableView.selectRow(at: indexPath, animated: false, scrollPosition: .middle)
                }

            }
        }
        
        
    }
    
    /// 视图即将可见
    ///
    /// - Parameter animated: <#animated description#>
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //设置标题栏为亮色
        setTitleBarLight()
        
        
        
    }
    
    /// 界面已经显示出来了
    ///
    /// - Parameter animated: <#animated description#>
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        scrollPosition()
    }
    
    /// 视图即将消失
    ///
    /// - Parameter animated: <#animated description#>
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //设置标题栏为默认颜色
        setTitleBarDefault()
    }
    
    /// 播放当前位置的音乐
    ///
    /// - Parameter position: <#position description#>
    func play(_ position:Int)  {
        //替换播放列表
        playListManager.setPlayList(dataArray)
        
        //从当前位置开始播放
        playListManager.play(position)
        
        pushMusicPlayerController()
        
        //跳转到简单播放界面
//        SimplePlayerController.start(navigationController!)
    }

    override func pageId() -> String? {
        return "SheetDetail"
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    deinit {
        DDLogDebug("SheetDetailController deinit")
    }

}

// MARK: - 启动方法
extension SheetDetailController {
    
    /// 启动方法
    ///
    /// - Parameters:
    ///   - navigationController: <#navigationController description#>
    ///   - id: <#id description#>
    static func start(_ navigationController:UINavigationController,_ id:String) {
        //获取到Storyboard
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        
        //创建控制器
        let controller=storyboard.instantiateViewController(withIdentifier: "SheetDetail") as! SheetDetailController
        
        //传递参数
        controller.id = id
        
        //将控制器压入导航控制器
        navigationController.pushViewController(controller, animated: true)
    }
}

// MARK: - TableView数据源和代理
extension SheetDetailController: UITableViewDataSource,UITableViewDelegate {
    
    /// 有多少行
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    /// 返回Cell
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //获取Cell
        
        let cell=tableView.dequeueReusableCell(withIdentifier: SongListCell.NAME) as! SongListCell
        
        //设置Tag
        //目的是在Cell中显示当前音乐位置
        cell.tag = indexPath.row
        
        //绑定数据
        cell.bindData(dataArray[indexPath.row])
        
        //返回Cell
        return cell
    }
    
    /// 返回Header
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        //获取Header
        header = tableView.dequeueReusableHeaderFooterView(withIdentifier: SheetDetailHeaderView.NAME) as! SheetDetailHeaderView
        
        //设置评论列表点击回调方法
        header.onCommentClick = {[weak self] in
            if let s = self {
                print("SheetDetailController onCommentClick:\(s.data.title)")

                CommentController.start(s.navigationController!, sheet: s.data.id)
            }
        }

        //设置收藏点击回调方法
        header.onCollectionClick = {[weak self] in
            print("SheetDetailController onCollectionClick")
            self?.processCollectionClick()
        }

        //设置用户点击回调方法
        header.onUserClick = {[weak self] in
            if let self = self {
                print("SheetDetailController onUserClick")

                UserDetailController.start(self.navigationController!, userId: self.data.user.id)
            }
        }
        
        //播放全部点击回调方法
//        header.onPlayClick = {[weak self] in
//            print("SheetDetailController onPlayClick")
//
//            self?.play(0)
//        }
        
        weak var weakSelf = self
        header.onPlayClick = {
            print("SheetDetailController onPlayClick")

            weakSelf?.play(0)
        }
        
        //返回Header
        return header
    }
    
    /// 返回Header高度
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        //20(分割线)+140+20(分割线)+52+20(分割线)+55.5
        return 307.5
    }
    
    /// TableView滚动的时候就会调用
    ///
    /// - Parameter scrollView: <#scrollView description#>
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //垂直方向上滚动的距离
        //不滚动的时候为0
        //在0的位置向上滚动为正
        //在0的位置向下滚动为负
        let offsetY = scrollView.contentOffset.y
        
        print("SheetDetailController scrollViewDidScroll:\(offsetY)")
        
        //动态更改背景高度约束的值
        //导航栏+Heade高度=350（大概计算）
        backgroundContainerHeight.constant = 350 - offsetY
    }
    
    /// 点击Cell回调方法
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        play(indexPath.row)
        
        //跳转到简单播放界面
//        SimplePlayerController.start(navigationController!)
    }
    
}
